import axios from 'axios'
import router from '@/router/index'
import {
  Message
} from 'element-ui'

axios.interceptors.request.use(
  config => {
    const x_access_token = sessionStorage.getItem('Token')
    if (x_access_token) { // 有token时
      config.headers['Token'] = x_access_token // 给请求头加token
    }
    return config
  }, error => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    const { status } = response.data || {}
    switch (+status) {
      case 401:
        sessionStorage.removeItem('Token')
        Message({
          message: '登录过期！请重新登录！',
          type: 'error',
          duration: 6 * 1000
        })
        return router.push('/login')
      default:
        return response.data
    }
  },
  error => {
    const { status } = error.response || {}
    switch (+status) {
      case 401:
        sessionStorage.removeItem('Token')
        return router.push('/login')
      default:
        Promise.reject(error)
    }
  }
)

export default axios